package com.fingard.dsp.bank.directbank.cmb01.util;

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class DESUtils {
	static {
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
	}
	
	public static Cipher GetCipher(int opmode, String key) throws Exception {
		DESKeySpec dks = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		Key secretKey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
		cipher.init(opmode, secretKey);
		return cipher;
	}
	
	public static String encode(String data, String key) throws Exception {
		Cipher cipher = GetCipher(Cipher.ENCRYPT_MODE, key);
		byte[] byteHex = cipher.doFinal(data.getBytes("UTF-8"));
		return byteToHexString(byteHex);
	}
	
	public static String byteToHexString(byte[] bytes) {
		 StringBuffer sb = new StringBuffer(bytes.length);
		 String sTemp;
		 for (int i = 0; i < bytes.length; i++) {
			 sTemp = Integer.toHexString(0xFF & bytes[i]);
			 if (sTemp.length() < 2) {
				 sb.append(0);
			 }
			 sb.append(sTemp.toUpperCase());
		 }
		 return sb.toString();
	}
	
	public static void main(String[] args) throws Exception {
		String s = DESUtils.encode("E074FD4A3B7259ECC66A6093DAC24421","12345678");
		System.out.println(s);
	}
}
